package org.example.java.util.concurrency.threadlocal;

/**
 * 线程结束回收ThreadLocal对象
 *
 * Created by Juntao.Zhang on 2014/9/10.
 */
public class ThreadLocalGcTest {
  static class MyThreadLocal extends ThreadLocal {
    private byte[] a = new byte[1024 * 1024 * 1];

    @Override
    public void finalize() throws Throwable {
      System.out.println("My threadlocal 1 MB finalized.");
    }
  }

  static class My50MB {
    private byte[] a = new byte[1024 * 1024 * 50];

    //延长一次
    @Override
    public void finalize() throws Throwable {
      System.out.println("My 50 MB finalized.");
    }
  }

  static class Test {
    public static void main(String[] args) throws InterruptedException {
      ThreadLocal tl = new MyThreadLocal();
      tl.set(new My50MB());
      tl = null;
      System.out.println("Full GC");
      Thread.sleep(1000);
      System.gc();
      Thread.sleep(1000);
      System.gc();
      Thread.sleep(1000);
      System.gc();
    }
  }

  static class Test2 {
    public static void main(String[] args) throws InterruptedException {
      new Thread(new Runnable() {
        @Override
        public void run() {
          ThreadLocal tl = new MyThreadLocal();
          tl.set(new My50MB());
          tl = null;
          System.out.println("Full GC");
          System.gc();
        }
      }).start();

      Thread.sleep(1000);
      System.gc();
      Thread.sleep(1000);
      System.gc();
    }
  }

}
